package com.wang.socket;

import com.wang.conf.AppConf;
import com.wang.util.PrintUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Random;

public class NettySocketServer {


    private String hostIp = "127.0.0.1";


    public NettySocketServer() {
        //获取本机ip
        this.hostIp = getServerIp();
    }

    //第一步 获取ip
    public String getServerIp() {
        //第一步获取本机IP地址 打印出来
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String serverIp = addr.getHostAddress();
            PrintUtil.print("开始开启Socket服务,服务器IP: " + serverIp);
            return serverIp;

        } catch (UnknownHostException e) {
            PrintUtil.print("获取服务器IP失败");
            return null;
        }
    }

    @PostConstruct
    public void start() {

        PrintUtil.print("开始开启Socket服务,socket服务端口号：" + AppConf.socketPort);
        // 创建一个线程组,用来负责接收客户端连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 创建另一个线程组,用来负责 I/O 的读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建一个 Server 实例(可理解为 Netty 的入门类)
            ServerBootstrap b = new ServerBootstrap();
            // 将两个线程池设置到 Server 实例
            b.group(bossGroup, workerGroup).option(ChannelOption.SO_BACKLOG, 1024)  //设置接收缓冲区大小
                    // 设置 Netty 通道的类型为 NioServerSocket(非阻塞 I/O Socket 服务器)
                    .channel(NioServerSocketChannel.class)
                    // 设置建立连接之后的执行器(ServerInitializer 是我创建的一个自定义类)
                    .childHandler(new NettySocketChannelInitializer());
            // 绑定端口并且进行同步
            ChannelFuture future = b.bind(AppConf.socketPort).sync();
            // 对关闭通道进行监听
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 资源关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }





/*    private class  ChildChannelHandler extends ChannelInitializer<SocketChannel> {


        protected void initChannel(SocketChannel ch) throws Exception {

            ch.pipeline().addLast(new InBoundHandler());
        }
    }*/

}
